***CBSA-level leverage and other covariates******

clear
set more off

use CYd2i2006nyf_frommiansufi_20120621.dta 

drop d2i2006

rename d2inyf d2i
drop county

merge m:1 fips using countyCBSAmap.dta
keep if _merge==3
drop _merge

sort cbsa year
by cbsa year:egen totpop=total(pop)
gen d2irat=d2i*pop2k/totpop

collapse(sum) d2irat, by(cbsa year)
rename d2irat d2i

save CBSAdebtLong.dta, replace

reshape wide d2i, i(cbsa) j(year)

save CBSAdebtWide.dta, replace


*********************CBSA-level covariates*******************
use miansufieconometrica_countylevel.dta, clear /*from Sufi's website*/

keep fips netw elas total white-urban
merge m:1 fips using countyCBSAmap.dta
corr total pop
sort cbsa 
by cbsa :egen totpop2k=total(pop)
gen netwCBSA=netwp*pop2k/totpop
by cbsa :egen tothh=total(total)
gen netwCBSAhh=netwp*total/tothh


gen ratio=pop2k/totpop
gen elasCBSA=elas*ratio
foreach var of varlist white-urban{
  gen `var'CBSA=ratio*`var'
}

collapse(sum) *CBSA, by(cbsa)

save MSdataCBSA, replace


